package rpc.frame.core.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;
import rpc.frame.core.data.RpcRequest;
import rpc.frame.core.data.RpcResponse;
import rpc.frame.core.util.ProtostuffUtil;

import java.util.List;

@Slf4j
public class RpcRequestEncoder extends MessageToMessageEncoder<RpcRequest> {

    /**
     * 加码 将object 序列化成字节码
     * @param ctx
     * @param rpcRequest
     * @param list
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, RpcRequest rpcRequest, List<Object> list) throws Exception {
        try {
            byte[] serialize = ProtostuffUtil.serialize(rpcRequest);
            ByteBuf buffer = ctx.alloc().buffer(serialize.length);
            buffer.writeBytes(serialize);
            list.add(buffer);
        } catch (Exception e) {
            log.error("RpcResponseEncoder error msg={}",e);
            throw new RuntimeException(e);
        }
    }
}
